#!/usr/bin/env groovy

def getServer() {
    def remote = [:]
    remote.name = 'manager node'
    remote.user = 'dev'
    remote.host = "${REMOTE_HOST}"
    remote.port = 22
    remote.identityFile = '/root/.ssh/id_rsa'
    remote.allowAnyHosts = true
    return remote
}

def call(Map map) {

    pipeline {
        agent any

        environment {
            REMOTE_HOST = "${map.REMOTE_HOST}"
            REPO_URL = "${map.REPO_URL}"
            BRANCH_NAME = "${map.BRANCH_NAME}"
            STACK_NAME = "${map.STACK_NAME}"
            Registry_Domain = "116.8.109.23:18188";
            Registry_Addr = "${Registry_Domain}/test";
            Registry_Username = "admin";
            Registry_Password = "Harbor12345";
            String0 =  "$params.servers"
        }

        stages {
            stage('获取代码') {
                steps {
                    git([credentialsId: "25d47fc8-3abf-4108-b73f-0e59da2bb06b", url: "${REPO_URL}", branch: "${BRANCH_NAME}"])
                }
            }

            stage('代码编译') {
                steps {
                    withMaven(maven: 'maven3.8.1') {
                        sh "/var/jenkins_home/tools/hudson.tasks.Maven_MavenInstallation/maven3.8.1/bin/mvn package -e -Ddockerfile.skip -Dmaven.test.skip=true"
                    }
                }
            }

            stage('检索Dockerfiles') {
                steps{
                    sh '''
                    Dockerfiles=`find -name Dockerfile`
                    echo "检索到Dockerfile：\\n%s\\n" "${Dockerfiles}"
                    j=0
                    for d in ${Dockerfiles} ; do
                        j=`expr $j + 1`
                    done
                    if [ "$j" -eq "0" ]; then
                        echo '没有检索到Dokcerfile\'
                        exit 1
                    fi
                    branch=${1:-master}
                    timestamp=`date +%Y%m%d%H%M%S`
                    files=`git diff --name-only HEAD~ HEAD`
                    echo "git提交的文件：\\n%s\\n" "${files}"
                    #登录镜像库
                    docker login --username=${Registry_Username} $Registry_Domain -p${Registry_Password}
                    for module in ${Dockerfiles}
                    do
                        module=`echo ${module%/*}`
                        module=`echo ${module##*/}`
                        echo "${module}"
                        if ( echo ${files} |grep -q $module );then
                            cd ${WORKSPACE}/$module
                            docker build --build-arg ACTIVE=${branch} -t ${Registry_Addr}/${module}:${branch}-${timestamp} .
                            docker tag ${Registry_Addr}/${module}:${branch}-${timestamp} ${Registry_Addr}/${module}:${branch}-latest
                            docker push ${Registry_Addr}/${module}:${branch}-latest
                            docker rmi -f ${Registry_Addr}/${module}:${branch}-${timestamp}
                        fi
                    done
                    echo "构建完成！"
                    '''
                }
            }

            stage('部署至Rancher'){
                steps {
                    //sh 'echo "${p_name}"'

                    script{
                        for (item in String0.tokenize(',')){
                            //echo "Deploying to " + item
                            rancherRedeploy alwaysPull: true, credential: 'jenkins-rancher', images: '116.8.109.23:18188/test/'+item+':last', workload: '/project/c-j6rbr:p-pznhc/workloads/deployment:default:'+item
                        }
//                        try{
//                            rancherRedeploy alwaysPull: true, credential: 'Rancher', images: '116.8.109.23:18188/test/deploy-upload:last', workload: '/project/c-j6rbr:p-pznhc/workloads/deployment:default:deploy-upload'
//                            for (item in String0.tokenize(',')){
//                                echo "Deploying to " + item
//                                rancherRedeploy alwaysPull: true, credential: 'Rancher', images: '${Registry_Addr}/${item}:${branch}-latest', workload: '/project/c-j6rbr:p-pznhc/workloads/deployment:default:'+item
//                            }
//                        rancherRedeploy alwaysPull: true, credential: 'jenkins-rancher', images: '116.8.109.23:18188/test/deploy-upload:last', workload: '/project/c-j6rbr:p-pznhc/workloads/deployment:default:deploy-upload'
//                        }catch(Exception err){
//                            //error "${err.toString()}"
                            error err
                            //err.message
                            //echo err;
//                        }
                    }

                }
            }

        }
    }
}
